/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ht6_huffman.gui;

import ht6_huffman.ArbolHuffman;
import ht6_huffman.Caracter;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author jorgelainfiesta
 */
public class main extends javax.swing.JFrame {

    private ArbolHuffman huffman;
    /**
     * Creates new form main
     */
    public main() {
        initComponents();
        model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                //Only the third column
                return false;
            }
        };
        tablaCaracteres.setModel(model);
        
        model.addColumn("Caracter");
        model.addColumn("Frecuencia");
        model.addColumn("Código");
        
        decodeBtn.setVisible(false);
        decodeIn.setVisible(false);
        decodeLabel.setVisible(false);
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        huffmanInput = new javax.swing.JTextField();
        generateBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaCaracteres = new javax.swing.JTable();
        jSeparator2 = new javax.swing.JSeparator();
        decodeLabel = new javax.swing.JLabel();
        decodeIn = new javax.swing.JTextField();
        decodeBtn = new javax.swing.JButton();
        outMensaje = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 2, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(102, 102, 102));
        jLabel1.setText("Implementación del algoritmo de Huffman");

        huffmanInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                huffmanInputActionPerformed(evt);
            }
        });

        generateBtn.setText("Generar");
        generateBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateBtnActionPerformed(evt);
            }
        });

        tablaCaracteres.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Caracter", "Frecuencia", "Código"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tablaCaracteres);

        decodeLabel.setForeground(new java.awt.Color(102, 102, 102));
        decodeLabel.setText("Decodificar:");

        decodeIn.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                decodeInKeyTyped(evt);
            }
        });

        decodeBtn.setText("Decodificar");
        decodeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                decodeBtnActionPerformed(evt);
            }
        });

        outMensaje.setFont(new java.awt.Font("Lucida Grande", 2, 15)); // NOI18N
        outMensaje.setForeground(new java.awt.Color(0, 153, 51));

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
            .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                .add(12, 12, 12)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(huffmanInput)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(generateBtn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 104, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(decodeIn)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(decodeBtn))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator2)
                            .add(jSeparator1)
                            .add(jScrollPane1))
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(decodeLabel)
                            .add(jLabel1))
                        .add(0, 0, Short.MAX_VALUE))))
            .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                .add(18, 18, 18)
                .add(outMensaje, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 437, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(12, 12, 12)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(huffmanInput, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(generateBtn))
                .add(18, 18, 18)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 119, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(decodeLabel)
                .add(6, 6, 6)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(decodeIn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(decodeBtn))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(outMensaje, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void huffmanInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_huffmanInputActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_huffmanInputActionPerformed

    private void generateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateBtnActionPerformed
        model.setRowCount(0);
        huffman = new ArbolHuffman(huffmanInput.getText());
        for(Caracter c : huffman.getAlfabeto()){
            model.addRow(new Object[]{c.getCaracter(), c.getFrecuencia(), c.getCodigo()});
        }
        
        decodeBtn.setVisible(true);
        decodeIn.setVisible(true);
        decodeLabel.setVisible(true);
    }//GEN-LAST:event_generateBtnActionPerformed

    private void decodeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decodeBtnActionPerformed
        try{
            outMensaje.setText(huffman.decode(decodeIn.getText()));
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }//GEN-LAST:event_decodeBtnActionPerformed

    private void decodeInKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_decodeInKeyTyped
        // TODO add your handling code here:
        if(evt.getKeyChar()!='0' || evt.getKeyChar() != '1'){
            String[] chars = decodeIn.getText().split("");
            String cadena = "";
            for(String c : chars){
                if(c.equals("1") || c.equals("0"))
                    cadena+=c;
            }
            decodeIn.setText(cadena);
        }
            
    }//GEN-LAST:event_decodeInKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new main().setVisible(true);
            }
        });
        
        
        
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton decodeBtn;
    private javax.swing.JTextField decodeIn;
    private javax.swing.JLabel decodeLabel;
    private javax.swing.JButton generateBtn;
    private javax.swing.JTextField huffmanInput;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel outMensaje;
    private javax.swing.JTable tablaCaracteres;
    // End of variables declaration//GEN-END:variables
    private DefaultTableModel model;
}
